package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.AttendanceDetail;
import com.isunland.managesystem.entity.AttendanceListOriginal;
import com.isunland.managesystem.entity.AttendanceParams;
import com.isunland.managesystem.entity.AttendanceQueryContent;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONException;

/**
 * 对象功能: 工作任务-人员考勤使用的地图,可以查看所有类型,禁用时间选择(因为必须是当天的)
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/4/10 9:52
 */

public class AttendanceMapLocalWorkFragment extends BaseFragment implements View.OnClickListener {
  //查询传递的参数
  public static final String EXTRA_QUERY =
      "com.isunland.managesystem.ui.AttendanceMapFragment.extra_query";
  //public static final String EXTRA_TYPE = "com.isunland.managesystem.ui.AttendanceMapFragment.EXTRA_TYPE";
  //public static final String EXTRA_NAMES =AttendanceMapLocalWorkFragment.class.getSimpleName()+"EXTRA_NAMES" ;
  public static final String EXTRA_PARAMS =
      AttendanceMapLocalWorkFragment.class.getSimpleName() + "EXTRA_PARAMS";
  protected static final String IN = "in";
  protected static final String OUT = "out";
  //protected static final String KEEP = "keep";
  protected static final String ALL = "";
  private static final int REQUEST_QUERY = 0;
  private MapView mMapView;
  private AMap aMap;
  private ArrayList<AttendanceDetail> mList;
  private TextView mtvEndDate;
  private TextView mtvStartDate;
  private TextView mtvType;

  private AttendanceQueryContent mqueryContent;
  private String mCheckType = IN;
  private String mBegincheckTime;
  private String mEndcheckTime;
  private String mNames;
  private String mJobNos;

  //public AMapLocationClient mLocationClient;
  //private MyLocationListener mLocationListener;
  //List<LatLng> mlatLngs = new ArrayList<>();
  private View mView;

  public static Fragment newInstance(BaseParams params) {
    AttendanceMapLocalWorkFragment fragment = new AttendanceMapLocalWorkFragment();
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_PARAMS, params);
    fragment.setArguments(args);
    return fragment;
  }

  public void initData() {
    setTitleCustom(R.string.sign_map);
    CurrentUser user = CurrentUser.newInstance(getActivity());
    mCheckType = ALL;
    AttendanceParams params = (AttendanceParams) getArguments().getSerializable(EXTRA_PARAMS);
    mNames =
        MyStringUtil.getStringByDefault(params != null ? params.getNames() : user.getRealName(),
            user.getRealName());
    mJobNos =
        MyStringUtil.getStringByDefault(params != null ? params.getJobNos() : user.getJobNumber(),
            user.getJobNumber());
    mBegincheckTime = MyStringUtil.getStringByDefault(
        params != null ? params.getStartDate() : MyDateUtil.getFirstDay(),
        MyDateUtil.getFirstDay());
    mEndcheckTime = MyStringUtil.getStringByDefault(
        params != null ? params.getEndDate() : MyDateUtil.getLastDay(), MyDateUtil.getLastDay());
    volleyPostList();
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    initData();
    mView = inflater.inflate(R.layout.fragment_attendance_map, container, false);
    initView(savedInstanceState);
    return mView;
  }

  //@Override
  //public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  //    inflater.inflate(R.menu.menu_query, menu);
  //}

  private void initView(Bundle savedInstanceState) {
    //LinearLayout mllMapHeader = (LinearLayout) mView.findViewById(R.id.ll_mapHeader);
    mtvType = (TextView) mView.findViewById(R.id.tv_name_signHeader);
    mtvStartDate = (TextView) mView.findViewById(R.id.tv_startDate_signHeader);
    mtvEndDate = (TextView) mView.findViewById(R.id.tv_endDate_signHeader);
    mMapView = (MapView) mView.findViewById(R.id.mv_map);
    //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
    mMapView.onCreate(savedInstanceState);
    //初始化地图变量
    if (aMap == null) {
      aMap = mMapView.getMap();
    }
    updateHeader();
    //mllMapHeader.setOnClickListener(this);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_query:
        startQueryActivity();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void startQueryActivity() {
    mqueryContent =
        new AttendanceQueryContent(mNames, mJobNos, mCheckType, mBegincheckTime, mEndcheckTime);
    Intent query = new Intent(getActivity(), AttendanceQueryActivity.class);
    query.putExtra(EXTRA_QUERY, mqueryContent);
    startActivityForResult(query, REQUEST_QUERY);
  }

  private void volleyPostList() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_SIGN_LIST);
    ParamsNotEmpty params = new ParamsNotEmpty();

    params.put("rows", "1000");
    params.put("jobNos", mJobNos);
    params.put("begindate", mBegincheckTime);
    params.put("enddate", mEndcheckTime);

    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        AttendanceListOriginal attendanceListOriginal =
            new Gson().fromJson(arg0, AttendanceListOriginal.class);
        List<AttendanceDetail> attendanceDetail = attendanceListOriginal.getList();
        if (mList == null) {
          mList = new ArrayList<>();
        }
        mList.clear();
        mList.addAll(attendanceDetail);
        initMap(mList);//地图缩放级别
        initMark();
      }
    }, false, false);
  }

  private void initMap(List<AttendanceDetail> mList) {
    for (int i = 0; i < mList.size(); i++) {
      if (!TextUtils.isEmpty(mList.get(i).getLatitude()) && !TextUtils.isEmpty(
          mList.get(i).getLongitude())) {
        double lat = Double.parseDouble(mList.get(i).getLatitude());
        double lon = Double.parseDouble(mList.get(i).getLongitude());
        CameraUpdate cameraUpdate =
            CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(lat, lon),//新的中心点坐标
                12, //新的缩放级别
                0, //俯仰角0°~45°（垂直与地图时为0）
                0  ////偏航角 0~360° (正北方为0)
            ));
        aMap.animateCamera(cameraUpdate);
        break;
      }
    }
  }

  private void updateHeader() {
    //if (IN.equalsIgnoreCase(mCheckType)) {
    //    mtvType.setText("类型<" + "签到" + ">");
    //} else if (OUT.equalsIgnoreCase(mCheckType)) {
    //    mtvType.setText("类型<" + "签退" + ">");
    //} else if (KEEP.equalsIgnoreCase(mCheckType)) {
    //    mtvType.setText("类型<" + "外勤" + ">");
    //}
    //else if (ALL.equalsIgnoreCase(mCheckType)) {
    //    mtvType.setText("类型<" + "全部" + ">");
    //}
    mtvType.setText(
        MyStringUtil.connect(getString(R.string.staff), getString(R.string.lessThan), mNames,
            getString(R.string.moreThan)));
    mtvStartDate.setText(mBegincheckTime);
    mtvEndDate.setText(mEndcheckTime);
  }

  private void initMark() {
    if (IN.equalsIgnoreCase(mCheckType) || OUT.equalsIgnoreCase(mCheckType) || ALL.equalsIgnoreCase(
        mCheckType)) {
      //画点标记
      paintMark();
    } else {
      //画折线
      paintLine();
    }
  }

  private void paintLine() {
    //        List<LatLng> latLngs = new ArrayList<LatLng>();
    //        latLngs.add(new LatLng(39.999391, 116.135972));
    //        latLngs.add(new LatLng(39.898323, 116.057694));
    //        initPolyline(latLngs);
    //        List<LatLng> latLngs1 = new ArrayList<LatLng>();
    //        latLngs1.add(new LatLng(39.900430, 116.265061));
    //        latLngs1.add(new LatLng(39.955192, 116.140092));
    //        initPolyline(latLngs1);

    List<LatLng> latLngs = new ArrayList<>();
    String outId = "";
    boolean ifFirst = true;//是否是一条线的开始
    for (int i = 0; i < mList.size(); i++) {
      if (!TextUtils.isEmpty(mList.get(i).getOutId())) {
        if (ifFirst) {
          outId = mList.get(i).getOutId();
        }
        //当id 相同时
        if (outId.equalsIgnoreCase(mList.get(i).getOutId())) {
          if (!TextUtils.isEmpty(mList.get(i).getLatitude()) && !TextUtils.isEmpty(
              mList.get(i).getLongitude())) {
            double lat = Double.parseDouble(mList.get(i).getLatitude());
            double lon = Double.parseDouble(mList.get(i).getLongitude());
            latLngs.add(new LatLng(lat, lon));
            ifFirst = false;
          }
        } else {
          if (latLngs.size() != 0) {
            initPolyline(latLngs);
            latLngs.clear();
            ifFirst = true;
          }
        }
      } else {
        if (latLngs.size() != 0) {
          initPolyline(latLngs);
          latLngs.clear();
          ifFirst = true;
        }
      }
    }
    if (latLngs.size() > 0) {
      initPolyline(latLngs);
    }
  }

  private void initPolyline(List<LatLng> latLngs) {
    Marker start = aMap.addMarker(new MarkerOptions().position(
        new LatLng(latLngs.get(latLngs.size() - 1).latitude,
            latLngs.get(latLngs.size() - 1).longitude))
        .title("起点")
        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
    Marker finish = aMap.addMarker(
        new MarkerOptions().position(new LatLng(latLngs.get(0).latitude, latLngs.get(0).longitude))
            .title("终点")
            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
    //Polyline polyline = aMap.addPolyline(new PolylineOptions().addAll(latLngs).width(5)
    //        .color(Color.argb(255, new Random().nextInt(256), new Random().nextInt(256), new Random().nextInt(256))));
    start.showInfoWindow();
    finish.showInfoWindow();
  }

  private void paintMark() {
    for (int i = 0; i < mList.size(); i++) {
      if (!TextUtils.isEmpty(mList.get(i).getLatitude()) && !TextUtils.isEmpty(
          mList.get(i).getLongitude())) {
        double lat = Double.parseDouble(mList.get(i).getLatitude());
        double lon = Double.parseDouble(mList.get(i).getLongitude());
        LatLng latLng = new LatLng(lat, lon);
        @SuppressWarnings("deprecation") Marker marker = aMap.addMarker(
            new MarkerOptions().position(latLng)
                .title(mList.get(i).getName())
                .snippet(MyStringUtil.connect(
                    MyDateUtil.dateToString(new Date(mList.get(i).getCheckTime()),
                        MyDateUtil.TYPE_ALL), getString(R.string.lineBreak),
                    mList.get(i).getLocation())));
        if (AttendanceDetail.TYPE_IN == mList.get(i).getCheckType()) {
          marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
        }
        if (AttendanceDetail.TYPE_OUT == mList.get(i).getCheckType()) {
          marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
        }
        if (AttendanceDetail.TYPE_KEEP == mList.get(i).getCheckType()) {
          marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
        }
      }
    }
  }

  @Override public void onDestroy() {
    super.onDestroy();
    //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
    mMapView.onDestroy();
  }

  @Override public void onResume() {
    super.onResume();
    //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
    mMapView.onResume();
  }

  @Override public void onPause() {
    super.onPause();
    //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
    mMapView.onPause();
  }

  @Override public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
    mMapView.onSaveInstanceState(outState);
  }

  //private void getLocation() {
  //    mLocationListener = new MyLocationListener();
  //    mLocationClient = new AMapLocationClient(getActivity());
  //    AMapLocationClientOption locationOption = new AMapLocationClientOption();
  //    // 设置定位模式为高精度模式
  //    locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
  //    locationOption.setInterval(3000);
  //
  //    // 设置定位监听
  //    mLocationClient.setLocationListener(mLocationListener);
  //    // 设置定位参数
  //    mLocationClient.setLocationOption(locationOption);
  //    // 启动定位
  //    mLocationClient.startLocation();
  //
  //}

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_QUERY) {
      mqueryContent = (AttendanceQueryContent) data.getSerializableExtra(EXTRA_QUERY);
      mNames = mqueryContent.getName();
      mJobNos = mqueryContent.getJobNos();
      mCheckType = mqueryContent.getCheckType();
      mBegincheckTime = mqueryContent.getBegincheckTime();
      mEndcheckTime = mqueryContent.getEndcheckTime();
      updateHeader();
      aMap.clear();// 清理之前的图标

      //            if (KEEP.equalsIgnoreCase(mCheckType)) {
      //                CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(
      //                        new LatLng(40.041448, 116.30837),//新的中心点坐标
      //                        15, //新的缩放级别
      //                        0, //俯仰角0°~45°（垂直与地图时为0）
      //                        0  ////偏航角 0~360° (正北方为0)
      //                ));
      //                aMap.animateCamera(cameraUpdate);
      //                getLocation();
      //            } else {
      volleyPostList();
      //            }
    }
  }

  //public class MyLocationListener implements AMapLocationListener {
  //
  //    @Override
  //    public void onLocationChanged(AMapLocation location) {
  //
  //        if (location == null || location.getErrorCode() != 0) {
  //            return;
  //        }
  //        double latitude = location.getLatitude();
  //        double longtitude = location.getLongitude();
  //        mlatLngs.add(new LatLng(latitude, longtitude));
  //        Log.i("外勤location====", "latitude=" + latitude + ",longtitude=" + longtitude);
  //        if (mlatLngs.size() >= 0) {
  //            aMap.clear();
  //            //Marker marker1 = aMap.addMarker(new MarkerOptions()
  //            //        .position(new LatLng(mlatLngs.get(0).latitude, mlatLngs.get(0).longitude))
  //            //        .title("起点")
  //            //);
  //            //Marker marker = aMap.addMarker(new MarkerOptions()
  //            //        .position(new LatLng(mlatLngs.get(mlatLngs.size() - 1).latitude, mlatLngs.get(mlatLngs.size() - 1).longitude))
  //            //        .title("经度=" + latitude)
  //            //        .snippet("纬度=" + longtitude)
  //            //        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
  //            //);
  //            //Polyline polyline = aMap.addPolyline(new PolylineOptions()
  //            //        .addAll(mlatLngs)
  //            //        .width(5)
  //            //        .color(Color.RED)
  //            //);
  //        }
  //    }
  //}

  //    public static AttendanceMapFragment newInstance(ArrayList<AttendanceDetail> mList, String type) {
  //        AttendanceMapFragment mfragment = new AttendanceMapFragment();
  //        Bundle bundle = new Bundle();
  //        bundle.putSerializable(AttendanceListFragment.EXTRA_QUERY, mList);
  //        bundle.putSerializable(EXTRA_TYPE, type);
  //        mfragment.setArguments(bundle);
  //        return mfragment;
  //    }

  @Override public void onClick(View view) {
    switch (view.getId()) {
      case R.id.ll_mapHeader:
        startQueryActivity();
        break;
    }
  }
}
